#version 450 core

layout (location = 0) out vec4 o_Color;
//out int o_EntityID;

struct VertexOutput
{
	vec4 Color;
	vec2 TexCoord;
	float TilingFactor;
	vec2 UV;
};

layout (location = 0) in VertexOutput Output;
layout (location = 4) in float v_TexIndex;
layout (location = 5) in flat int v_EntityID;

uniform mediump vec2 TextureSize0;
uniform lowp float Time; 

uniform sampler2D u_Textures[5];
uniform sampler2D TextTexture;
uniform sampler2D NoiseTexture;

#define PI 3.1415926
#define CELLS vec2(64.0,30.0)
#define FALLERS 9.0
#define FALLERHEIGHT 12.0

vec2 rand(vec2 uv) {
    return floor(abs(mod(cos(
        uv * 652.6345 + uv.yx * 534.375 +
        0.001*cos(Time * PI / 100.) * dot(uv, texture(NoiseTexture, uv).xy)),
     0.001)) * 16000.0);
}

float fallerSpeed(float col, float faller) {
    return mod(cos(col * 363.435  + faller * 234.323), 0.1) * 1.0 + 0.3;
}


void main()
{
	vec4 texColor = Output.Color;
    vec2 uv = Output.TexCoord * Output.TilingFactor;
    vec2 UV = uv;

	switch(int(v_TexIndex))
	{
		case  0: texColor *= texture(u_Textures[0], uv); break;
	}

    float ratio = TextureSize0.x / TextureSize0.y;
	//uv.x *= ratio;
	uv.y = 1.0 - uv.y;

	// the rain part
    vec2 pix = mod(uv, 1.0/CELLS);
    vec2 cell = (uv - pix) * CELLS;
    pix *= CELLS * vec2(0.8, 1.0) + vec2(0.1, 0.0);
   
    float c = texture(TextTexture, (rand(cell) + pix) / 16.0).x;
    
    float b = 0.0;
    for (float i = 0.0; i < FALLERS; ++i) {
        float f = 3.0 - cell.y * 0.05 -
            mod((Time + i * 3534.34) * fallerSpeed(cell.x, i), FALLERHEIGHT);
        if (f > 0.0 && f < 1.0)
            b += f;
    }
    
    vec4 layer1 = vec4(0. ,b*c , 0. , 0.9);

	texColor *= vec4(0.5);//darker
	texColor += layer1;

	if (texColor.a == 0.0)
		discard;

	o_Color = texColor;
	//o_Color = vec4(uv.x, uv.y, 0.0, 1.0);
}
